#include <iostream>

#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/HttpMessage.h>
#include <workflow/HttpUtil.h>

using std::cout;
using std::endl;

void callback(WFHttpTask * httpTask)
{
    auto req = httpTask->get_req();
    auto resp = httpTask->get_resp();

    int state = httpTask->get_state();
    int error = httpTask->get_error();
    switch(state){
    case WFT_STATE_SYS_ERROR:
        fprintf(stderr, "system error: %s\n", strerror(error)); break;
    case WFT_STATE_DNS_ERROR:
        fprintf(stderr, "dns error: %s\n", gai_strerror(error)); break;
    case WFT_STATE_SUCCESS:
        break;
    }

    if(state != WFT_STATE_SUCCESS) {
        printf("error occurs!\n");
        return;
    }

    printf("%s %s %s\n", req->get_method(), 
           req->get_request_uri(),
           req->get_http_version());

    protocol::HttpHeaderCursor cursor(req);
    std::string key, value;
    while(cursor.next(key, value)) {
        cout << key << ":" << value << endl;
    }
    cout << endl;

    printf("%s %s %s\n", resp->get_http_version(),
           resp->get_status_code(),
           resp->get_reason_phrase());

    protocol::HttpHeaderCursor cursor2(resp);
    while(cursor2.next(key, value)) {
        cout << key << ":" << value << endl;
    }
    cout << endl;

    const void * body;
    size_t sz;
    resp->get_parsed_body(&body, &sz);
}

void test0()
{
    auto httpTask = WFTaskFactory::create_http_task("http://www.baidu.com", 0, 0, callback);

    httpTask->start();
}


int main()
{
    test0();
    return 0;
}

